import QueryMaterial2 from "@/components/QueryMaterial2";
import QueryUserDefine from "@/components/QueryUserDefine";
import QueryVendor from "@/components/QueryVendor";
import { s_getcommontableinfo, s_getProduceInfo, s_getPurchaseInfo, s_getSelectData, s_operateInfo, s_purchase_updateInfo, s_updateInfo, state2text, status2text } from "@/services/basis";
import { ActionType, EditableFormInstance, EditableProTable, parseValueToDay, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDateRangePicker, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components"
import { Button, Col, message, Modal, Row, Space, Tag ,Image} from "antd";
import moment from "moment";
import { useEffect, useRef, useState } from "react";
import { getSelection } from "@/services/selections";
import { DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";
import { random } from "lodash";
import ImportData from "@/components/ImportData";
import { useModel } from "@umijs/max";

const App:React.FC=()=>{
  const [open,setOpen]=useState(false);
  const [etype,setEtype]=useState(1);
  const [selectedRecord,setSelectRecord]=useState<DataType[]>([]);
 
  const actionRef=useRef<ActionType>();
  const formRef_main=useRef<ProFormInstance>();
  const actionRef_detail=useRef<ActionType>();
  const editableRef_detail=useRef<EditableFormInstance>();
   const [moptions,setMoptions]=useState([]);
  const[selectedDetail,setSelectedDetail]=useState([]);
  const [dataSource,setDataSource]=useState([]);
  const [total,setTotal]=useState(0);

  const { initialState, setInitialState } = useModel('@@initialState');
  const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);
 
interface DataType{
    rid?:number,
    id:number,x_id:number,material_id:number,userdefine_id:string,userdefine_name:string,
    code:string,name:string,invstd:string,munit_name:string,
    vendor_id:number,vendor_name:string, price:number,taxrate:number,begindate:string,enddate:string,
    status:number,operater_id:number,operate_time:string,isdefault?:number,
   }

   const columns:ProColumns<DataType>[]=[
    // {dataIndex:'id',title:'ID',search:false},
    {dataIndex:'x_id',hidden:true,search:false},{dataIndex:'material_id',hidden:true,search:false},
    // {dataIndex:'rid',title:'rid',search:false},
    {dataIndex:'pic',title:'图片',search:false,width:80,
    //   render:(text)=>{
    //       var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
    //       return <Image src={pic}  
    //              style={{width:50,height:50}} alt='无' />
    //   },
    // },
           render:(text,record,index,k)=>{
                         var pic="/basis_api/file/get2?filename="+record.code;
                         return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
       }},
    {dataIndex:'vendor_name',title:'供应商',width:100},
    {dataIndex:'code',title:'SKU编码' },{dataIndex:'name',title:'商品名称',width:100},
    {search:false,dataIndex:'invstd',title:'包装规格'},
    {dataIndex:'munit_name',title:'单位',search:false},
    {dataIndex:'vendor_id',hidden:true,search:false},
    {dataIndex:'price',title:'含税单价',search:false},{dataIndex:'taxrate',title:'税率%',search:false},
    // {dataIndex:'begindate',title:'生效日期',valueType:'date',width:100,search:false},
    // {dataIndex:'enddate',title:'截止时间',valueType:'date',width:100,search:false},
    {dataIndex:'isdefault',title:'是否默认',valueEnum:{1:{text:'是'},null:{text:'否'}},valueType:'select'},

    {dataIndex:'status',title:'状态',valueType:'select',width:80,
            valueEnum:{1:{text:'未审核'},5:{text:'已审核'},
            6:{text:'已弃审'},2:{text:'关闭'},3:{text:'删除'},9:{text:'全部'}}
        }, 
   ];

  interface DataTypeDetail{
      // id,vendor_id,material_id,price,taxrate,begindate,enddate,status,operater_id,operate_time,memo,
      //code,name,invstd,munit_name,pic,vendor_name,
       rid?:number,id?:number,vendor_id?:number,material_id?:number,price?:number,taxrate?:number,
       begindate?:string,enddate?:string,status?:number,operater_id?:number,operate_time?:string,
       code?:string,name?:string,invstd?:string,munit_name?:string,pic?:string,memo?:string,
       vendor_name?:string,isdefault?:number,
  };

  const columnsDetail:ProColumns<DataTypeDetail>[]=[
    {dataIndex:'rid',title:'rid'},
    {dataIndex:'pic',title:'图片',
      // render:(text)=>{
      //     var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
      //     return <Image src={pic}  
      //            style={{width:100,height:100}} alt='无' />
      // },
          render:(text,record,index,k)=>{
                         var pic="/basis_api/file/get2?filename="+record.code;
                         return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
       }
    },{dataIndex:'id',title:'id'},
    {dataIndex:'vendor_name',title:'供应商'},{dataIndex:'code',title:'SKU码'},{dataIndex:'name',title:'商品名称'},
    {dataIndex:'invstd',title:'包装规格'},{dataIndex:'munit_name',title:'单位'},{dataIndex:'price',title:'含税单价'},
    {dataIndex:'taxrate',title:'税率%'},
    // {dataIndex:'begindate',title:'生效日期',valueType:'date'},
    // {dataIndex:'enddate',title:'截止日期',valueType:'date'},
    {dataIndex:'isdefault',title:'是否默认',render:(text)=>text==1?'是':''},
    {dataIndex:'status',title:'状态',render:(text)=>text==1?'有效':'失效'}
  ];
  
   async function operateInfo(n:number){
     // source,x_id,operater_id,otype,id
      if(selectedRecord.length==0)
             message.warning('请选择要操作的行');
       else if(n==5&&selectedRecord[0].status==5)
                message.warning('此单据已审核，请不要重复操作');
       else if(n==6&&selectedRecord[0].status!=5)
                message.warning('此单据未审核，不能弃审');
       else{
             var ids=selectedRecord.map((item:any)=>item.id);
             const x=await s_operateInfo({x_id:1,source:'purchase_vendor_price',operater_id:initialState?.currentUser?.userid,
              otype:n,ids});
      if(x.success){
             message.success('操作成功');
             actionRef.current?.reloadAndRest?.();
        }else
            message.error('操作错误，请联系管理员。');
        } 
   };

   function add(){
        setEtype(1);
        setOpen(true);

   };

    function edit(){
      if(selectedRecord&&selectedRecord.length==0)
        message.warning('请先选择要编辑的行');
      else if(selectedRecord[0].status==2||selectedRecord[0].status==3||selectedRecord[0].status==5)
        message.warning('不能编辑已审核、已关闭或已删除单据。请选弃审或恢复。');
      else{
        setEtype(0);
        setOpen(true);
      };
   };

   function exitPrice(){
    setEtype(1);
    setOpen(false);
   }

   function submit(type:number){
      setEtype(type);
      formRef_main.current?.submit();   
   };

   async function savePrice(){
      var fdata=editableRef_detail.current?.getRowsData?.();
      if(fdata&&fdata.length>0)
           fdata=fdata?.map((item:any)=>{
            return {...item,
                    begindate:moment(moment(item.begindate).toDate()).format('YYYY-MM-DD HH:mm:ss'),
                    enddate:moment(moment(item.enddate).toDate()).format('YYYY-MM-DD HH:mm:ss'),
                   }
                });
        else 
           fdata=[];
      //  增加记录行
       if(etype==1){
          const vendor_id=formRef_main.current?.getFieldValue('vendor_id');
          const material_id=formRef_main.current?.getFieldValue('material_id');
          const price=formRef_main.current?.getFieldValue('price');
          const taxrate=formRef_main.current?.getFieldValue('taxrate');
          const status=formRef_main.current?.getFieldValue('status');
          const isdefault=formRef_main.current?.getFieldValue('isdefault');
          var begindate=formRef_main.current?.getFieldValue('begindate');
          var enddate=formRef_main.current?.getFieldValue('enddate');
          begindate=moment(moment(begindate).toDate()).format('YYYY-MM-DD HH:mm:ss');
          enddate=moment(moment(enddate).toDate()).format('YYYY-MM-DD HH:mm:ss');
          // const memo=formRef_main.current?.getFieldValue('vendor_id');
          
          // 获取商品和供应商相关信息
          const x=await s_getPurchaseInfo({x_id:1,source:'baseinfo',fdata:{vendor_id,material_id}});
          //更新表格
          const newt=[...fdata,
                 {
                  vendor_id:vendor_id,
                  vendor_name:x.data[0][0].vname,
                  material_id:material_id,
                  code:x.data[0][0].code,
                  name:x.data[0][0].name,
                  invstd:x.data[0][0].invstd,
                  munit_name:x.data[0][0].munit_name,
                  pic:x.data[0][0].pic,
                  price,taxrate,begindate,enddate,
                  status,isdefault,
                  rid:Math.random(),
                },
                ];

           formRef_main.current?.setFieldValue('editable_detail',newt);
          //  alert(JSON.stringify(newt));

       } 

      //  修改记录行
       else if(etype==2){
          const vendor_id=formRef_main.current?.getFieldValue('vendor_id');
          const material_id=formRef_main.current?.getFieldValue('material_id');
          const price=formRef_main.current?.getFieldValue('price');
          const taxrate=formRef_main.current?.getFieldValue('taxrate');
          var begindate=formRef_main.current?.getFieldValue('begindate');
          var enddate=formRef_main.current?.getFieldValue('enddate');
          begindate=moment(moment(begindate).toDate()).format('YYYY-MM-DD HH:mm:ss');
          enddate=moment(moment(enddate).toDate()).format('YYYY-MM-DD HH:mm:ss');
          const status=formRef_main.current?.getFieldValue('status');
          const id=formRef_main.current?.getFieldValue('id');
          const isdefault=formRef_main.current?.getFieldValue('isdefault');
          // const memo=formRef_main.current?.getFieldValue('vendor_id');

          var rid=selectedDetail[0].id;
           
          fdata=fdata.filter((item:any)=>item.id!=id||item.vendor_id!=vendor_id&&item.material_id!=material_id);
          // 获取商品和供应商相关信息
          const x=await s_getPurchaseInfo({x_id:1,source:'baseinfo',fdata:{vendor_id,material_id}});
          //更新表格
           
          const newt=[
               {
                  vendor_id:vendor_id,
                  vendor_name:x.data[0][0].vname,
                  material_id:material_id,
                  code:x.data[0][0].code,
                  name:x.data[0][0].name,
                  invstd:x.data[0][0].invstd,
                  munit_name:x.data[0][0].munit_name,
                  pic:x.data[0][0].pic,
                  price,taxrate,begindate,enddate,
                  status,id,isdefault,
                  rid:Math.random(),
                },
                ...fdata,
                
                ];
            
           formRef_main.current?.setFieldValue('editable_detail',newt);
       }
       
       //正式保存价格表
       else{
        // source,x_id,operater_id,etype,fdata
           const x=await s_purchase_updateInfo({x_id:1,source:'purchase_vendor_price',operater_id:initialState?.currentUser?.userid,fdata});
           if(x.success){
              message.success('价格保存成功');
              actionRef.current?.reloadAndRest?.();
           }
            else
              message.error('保存失败，请联系管理员');
       };
   };


  //  表单主体==================================================================================================
    return <>
      <ProCard title='供应商价格表' style={{height:'85vh'}}
           extra={<Space>
            <Button onClick={()=>add()} style={{width:100}}>新增</Button>
            <Button onClick={()=>edit()} style={{width:100}}>编辑</Button>
            <Button onClick={()=>operateInfo(5)}>审核</Button>
            <Button onClick={()=>operateInfo(6)}>取消审核</Button>
            <Button onClick={()=>operateInfo(2)} style={{width:100}}>关闭</Button>
            <Button onClick={()=>operateInfo(1)} style={{width:100}}>恢复</Button>
            <ImportData  x_id={1} source='importdata' tdata={{data:'vendor_priceschedule'}} operater_id={initialState?.currentUser?.userid}  />
           </Space>}
          >
           <ProTable<DataType> 
             rowKey='id'
             columns={columns}
             actionRef={actionRef}
             search={{span:4}}
             options={false}
            //  request={async (param)=>{
            //     const x=await s_getcommontableinfo({x_id:1,source:'v_purchase_vendor_price',id:0,fdata:param});
            //     setDataSource(x.data[0]);
            //     return {
            //     data:x.data[0],
            //     success:true,
            //    }
            //  }}
              request={async (param)=>{
                  const x=await s_getPurchaseInfo({source:'v_purchase_vendor_price',x_id:1,
                                    fdata:{id:0,param}});
                  setTotal(x.data[0][0].count);
                  return{
                       data:x.data[1],
                       success:true,
                        }
                }}
             rowSelection={{
              type:'checkbox',
              selectedRowKeys:selectedLineKeys,
              onChange(selectedRowKeys, selectedRows, info) {
                setSelectRecord(selectedRows);
                setSelectedLineKeys(selectedRowKeys);
              },
             }}
              onRow={(record)=>{
            return {
              onClick:()=>{
                const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                if(selectedLineKeys.includes(k)){
                    setSelectedLineKeys(selectedLineKeys.filter(item=>item.id!=k));
                    setSelectRecord( selectedRecord.filter(item=>item.id!=k));
                }
                else{
                     setSelectedLineKeys([...selectedLineKeys, k]);
                     setSelectRecord([...selectedRecord,record]);
                };
              },
            }
           }}
             scroll={{y:'55vh'}}
                    pagination={{
                    showQuickJumper:true,
                    showSizeChanger:true,
                    defaultPageSize:10,
                    defaultCurrent:1,
                    total,
                  }}
           />
            </ProCard>

           {/* 价格编辑界面---------------------------------------------------- */}
           <Modal open={open} closable destroyOnClose onCancel={()=>exitPrice()} onClose={()=>exitPrice()}
              width='90%' okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} style={{top:10}}
            >
            <ProCard title='供应商价格管理' style={{height:'90vh',overflow:'auto'}}
               extra={<Space>
                <Button onClick={()=>submit(1)}><PlusOutlined/>增加</Button>
                <Button onClick={()=>submit(2)}><EditOutlined/>修改</Button>
                <Button onClick={()=>submit(3)} >保存价格表</Button>
                <Button onClick={()=>exitPrice()}>退出</Button>
               </Space>}
               >
            <ProForm  submitter={false}   formRef={formRef_main}  
              onFinish={()=>savePrice()} 
              layout="horizontal" labelAlign="left" labelCol={{offset:0,span:6}}
              initialValues={etype==1?{status:1,isdefault:1}:{
                editable_detail:selectedRecord,
              }}
            >
              <Row gutter={8}>
                  <Col span={6}>
                     <ProFormText name='id' label='ID' />
                     <ProFormSelect name='vendor_id' label='供应商' width={300} 
                          rules={[{required:true,message:'必输项'}]}
                          showSearch
                          request={async ()=>{
                             const x=await s_getSelectData({x_id:1,source:'v_vendor'});
                             return x.data;
                               }}
                        />
                     <ProFormSelect name='material_id' label='SKU码' width={300} 
                         rules={[{required:true,message:'必输项'}]}
                         showSearch
                          options={moptions}
                         fieldProps={{
                           async onSearch(value) {
                           // alert(value);
                          const x=await s_getSelectData({x_id:1,source:'material_'+value});
                         setMoptions(x.data);
                      },
                 }}
                
            />
                  </Col>
                   <Col span={4}>
                     
                       <ProFormDigit name='price' label='含税单价'  width={200}
                            rules={[{required:true,message:'必须输入此项目'}]}
                       />
                       <ProFormDigit name='taxrate' label='税率%' width={200} 
                            rules={[{required:true,message:'必须输入此项目'}]}
                        />
                </Col>
                <Col span={4}>
                       <ProFormDatePicker name='begindate' label='生效日期'  width={200}
                            rules={[{required:true,message:'必须输入此项目'}]}
                       />
                       <ProFormDatePicker name='enddate' label='结束日期' width={200} 
                            rules={[{required:true,message:'必须输入此项目'}]}
                        />
                </Col>
                <Col span={4}>
                       <ProFormRadio.Group name='status' label='状态'
                         rules={[{required:true,message:'必须输入此项目'}]}
                          options={[{value:1,label:'有效'},{value:2,label:'关闭'}]}
                       />
                     <ProFormRadio.Group name='isdefault' label='是否默认' width={200} 
                          // rules={[{required:true,message:'必输项'}]}
                        options={[{value:0,label:'否'},{value:1,label:'是'}]}
                     />
                </Col>
               
              </Row>
              {/* <Row>
                 <Col span={4}>
                       <ProFormText name='memo' label='备注'  width={600} />
                </Col> */}
              {/* </Row> */}

            <EditableProTable<DataTypeDetail>
               rowKey='rid'
               name='editable_detail'
               actionRef={actionRef_detail}
               editableFormRef={editableRef_detail}
               options={false}
               search={false}
               columns={columnsDetail}
               recordCreatorProps={false}
               editable={{
                   type:'multiple'
               }}
               scroll={{y:'55vh'}}
               rowSelection={{
                   type:'radio',
                  async onChange(selectedRowKeys, selectedRows:any, info) {
                     if(selectedRows.length>0){
                         const x=await s_getSelectData({x_id:1,source:'material_'+selectedRows[0].code});
                         setMoptions(x.data);
                         formRef_main.current?.setFieldsValue({
                            vendor_id:selectedRows[0].vendor_id,
                            material_id:selectedRows[0].material_id,
                            price:selectedRows[0].price,
                            taxrate:selectedRows[0].taxrate,
                            begindate:selectedRows[0].begindate,
                            enddate:selectedRows[0].enddate,
                            status:selectedRows[0].status,
                            id:selectedRows[0].id,
                            isdefault:selectedRows[0].isdefault,
                        });
                        // alert(JSON.stringify(selectedRows[0]));
                        setSelectedDetail(selectedRows);
                      };
                   },
               }}
                 />
               
            </ProForm>  
            </ProCard>         
            </Modal>
      </>
}

export default App;